package com.kuizii.base.aspect;


import com.kuizii.base.config.AuditLogConfigProperties;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

@Component
public class DefaultAuditLogHandler implements IAuditLogHandler {

    @Autowired
    private AuditLogConfigProperties auditLogConfigProperties;


    @Override
    public String getUserName() {
        return null;
    }

    @Override
    public String getUserCode() {
        return null;
    }

    @Override
    public String getToken() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            if (StringUtils.isNotEmpty(auditLogConfigProperties.getTokenName())) {
                return request.getHeader(auditLogConfigProperties.getTokenName());
            }
        }
        return null;
    }

    @Override
    public String getApplicationId() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            return StringUtils.isEmpty(auditLogConfigProperties.getAppId()) ? request.getHeader("appId") : auditLogConfigProperties.getAppId();
        }
        return StringUtils.isEmpty(auditLogConfigProperties.getAppId()) ? null : auditLogConfigProperties.getAppId();
    }

    @Override
    public String getApplicationName() {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null) {
            HttpServletRequest request = ((ServletRequestAttributes) requestAttributes).getRequest();
            return StringUtils.isEmpty(auditLogConfigProperties.getAppName()) ? request.getHeader("appName") : auditLogConfigProperties.getAppName();
        }
        return StringUtils.isEmpty(auditLogConfigProperties.getAppName()) ? null : auditLogConfigProperties.getAppName();
    }
}
